package app.tasks.search;

import app.env.Data;
import app.agent.Schedule;
import app.agent.SearchAgent;
import app.util.AppUtils;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @Name: PlayBehaviours
 * @Description:
 * @Author: colfish
 * @Date: 2021/4/10 23:05
 * 好好学习，天天向上！
 */
public class SearchSignal extends OneShotBehaviour {

    private SearchAgent searchAgent;
    private Logger logger = LogManager.getLogger(this.getClass());

    int nextState;

    public SearchSignal(SearchAgent searchAgent){
        this.searchAgent = searchAgent;
        nextState = 1;
    }

    @Override
    public void action() {
        nextState = 1;
        searchAgent.calculateSignal();
        ACLMessage signalMessage =new ACLMessage(ACLMessage.INFORM);
        AID receiver = Schedule.IDENTIFIER;
        String selfPos = searchAgent.position.toString();
        if(searchAgent.findTarget){
            // 找到了目标代理的位置
            // 1. 将搜索到目标的信息+目标代理位置+自身位置发送给管理员
            signalMessage.setContent(Data.FIND_TARGET+ ";" + searchAgent.targetPosition.toString()+";" + selfPos);
            signalMessage.addReceiver(receiver);
            searchAgent.send(signalMessage);
            logger.info(AppUtils.logMessage(searchAgent.getAID(), receiver, signalMessage));
        }else{
            // 没有找到目标代理的位置
            if(searchAgent.signal !=null){
                // 1. 将未搜索到目标的信息+信号值+自身位置发送给管理员
                signalMessage.setContent(Data.NOT_FIND_TARGET+ ";" + searchAgent.signal.toString() + ";" + selfPos);
                signalMessage.addReceiver(receiver);
                searchAgent.send(signalMessage);
                logger.info(AppUtils.logMessage(searchAgent.getAID(), receiver, signalMessage));
            }
        }
    }

    @Override
    public int onEnd() {
        return nextState;
    }
}
